package com.etong.frame.directive.impl.database;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PlaceholderCreator {
	protected static final Logger logger = LoggerFactory
			.getLogger(PlaceholderCreator.class);

	/**
	 * @Title : createPlaceholders
	 * @Description : 创建用于替换的变量
	 * @params
	 * @param expr
	 * @return 设定文件
	 * @return List<Placeholder> 返回类型
	 * @throws
	 */
	public static List<Placeholder> createPlaceholders(String expr,
			boolean required) {
		List<Placeholder> placeholders = new ArrayList<Placeholder>();

		if (null == expr || expr.isEmpty()) {
			logger.warn("Empty expr create placeholders");
			return placeholders;
		}

		Pattern pattern = Pattern.compile("(\\$\\{(\\w+)(,[^\\}.]*)*\\})");
		Matcher matcher = pattern.matcher(expr);
		while (matcher.find()) {
			Placeholder placeholder = new Placeholder();

			placeholder.setName(matcher.group(2));
			placeholder.setPlaceholder(matcher.group(1));
			if (null != matcher.group(3)) {
				placeholder.setProperty(matcher.group(3));
			}
			if (required) {
				placeholder.setRequired(required);
			}
			placeholders.add(placeholder);
		}
		return placeholders;
	}
}
